var express = require('express');
var router = express.Router();

const { ResultSuccess, ResultError } = require('../utils/result')
const { loginCheck } = require('../utils/tools')
const { getList, getDetail, newBlog, updateBlog, delBlog } =  require('../controller/blog')

// 获取博客列表
router.get('/list', function (req, res, next) {
  // 获取 query
  let author = req.query.author || ''
  let keyword = req.query.keyword || ''

  if (req.query.isadmin) {
    console.log('is admin')
    // 管理员界面
    if (req.session.username == null) {
      console.error('is admin, but no login')
      // 未登录
      return res.json(new ResultError('未登录'))
    }
    // 强制查询自己的博客
    author = req.session.username
  }
  // 调用 controller 处理业务逻辑
  const result = getList(author, keyword)
  result.then(data => {
    res.json(new ResultSuccess(data))
  })
});

// 获取博客详情
router.get('/detail', function (req, res, next) {
  const result = getDetail(req.query.id)
  result.then(data => {
    res.json(new ResultSuccess(data))
  })
});

// 新建一篇博客
router.post('/new', loginCheck, function (req, res, next) {
  req.body.author = req.session.username
  const result = newBlog(req.body)
  result.then(data => {
    res.json(new ResultSuccess(data))
  })
});

// 更新一篇博客
router.post('/update', loginCheck, function (req, res, next) {
  const result = updateBlog(id, req.body)
  result.then(data => {
    if (data) {
      res.json(new ResultSuccess('更新成功'))
    } else {
      res.json(new ResultError('更新失败'))
    }
  })
});

// 删除一篇博客
router.post('/del', loginCheck, function (req, res, next) {
  const author = req.session.username
  const result = delBlog(id, author)
  result.then(data => {
    if (data) {
      res.json(new ResultSuccess('删除成功'))
    } else {
      res.json(new ResultError('删除失败'))
    }
  })
});

module.exports = router;
